package main

import (
	"common/ws_contact"
	"context"
	"crypto/tls"
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

//func main() {
//	hub := ws_contact.NewHub()
//	go hub.Run(context.Background())
//	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
//		var err error = nil
//		nodeId := r.Header.Get("Sec-WebSocket-Protocol")
//		fmt.Println("r.Header:", r.Header)
//		if nodeId == "" {
//			w.WriteHeader(401)
//			fmt.Println(err)
//			return
//		}
//		ws_contact.ServeWs(hub, nil, nodeId, w, r)	})
//	log.Println("WebSocket server started on :10007")
//	err := http.ListenAndServe(":10007", nil)
//	if err != nil {
//		log.Fatal("ListenAndServe: ", err)
//	}
//}
func main() {

	hub := ws_contact.NewHub()
	go hub.Run(context.Background())

	root := mux.NewRouter()
	root.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		var err error = nil
		nodeId := r.Header.Get("Sec-WebSocket-Protocol")
		fmt.Println("r.Header:", r.Header)
		if nodeId == "" {
			w.WriteHeader(401)
			fmt.Println(err)
			return
		}
		ws_contact.ServeWs(hub, nil, nodeId, w, r)
	})
	log.Println("WebSocket server started on :10007")
	var err error

	cert, err := tls.LoadX509KeyPair("/opt/estore/estore.guanjieai.com.pem",
		"/opt/estore/estore.guanjieai.com.key")
	if err != nil {
		log.Println(err)
		return
	}
	tlsConfig := &tls.Config{Certificates: []tls.Certificate{cert}}
	listener1, err := tls.Listen("tcp", ":10007", tlsConfig)

	//listener, err := net.Listen("tcp", ":10007")
	//if err != nil {
	//	fmt.Println(err)
	//	return
	//}
	var server http.Server
	server.Handler = root
	fmt.Println("listent 10007")
	err = server.Serve(listener1)

	//err := http.ListenAndServe(":10007", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
